<template>
	<view class="page">
		<view class="container">
			<!-- 状态显示 -->
			<view class="status-section">
				<view v-if="!adapterState.available" class="status-item warn">
					<text class="status-icon">⚠️</text>
					<text class="status-text">蓝牙未开启</text>
				</view>
				<view v-else-if="scanning" class="status-item info">
					<text class="status-icon">🔍</text>
					<text class="status-text">正在扫描 BT04-A 设备...</text>
				</view>
				<view v-else-if="connecting" class="status-item info">
					<text class="status-icon">⏳</text>
					<text class="status-text">正在连接设备...</text>
				</view>
				<view v-else-if="connected" class="status-item success">
					<text class="status-icon">✅</text>
					<text class="status-text">已连接: {{ connectedDeviceName }}</text>
				</view>
				<view v-else class="status-item info">
					<text class="status-icon">ℹ️</text>
					<text class="status-text">点击下方按钮开始扫描 BT04-A 设备</text>
				</view>
			</view>

			<!-- 配对码输入 -->
			<view v-if="!connected" class="pairing-section">
				<text class="section-title">配对设置</text>
				<view class="input-group">
					<text class="input-label">配对密码</text>
					<input class="input-field" type="text" v-model="pairingPassword" placeholder="请输入配对密码" />
				</view>
				<view class="input-tips">
					<text class="tips-text">默认配对密码: 1234</text>
				</view>
			</view>

			<!-- 设备列表 -->
			<view v-if="filteredDevices.length > 0" class="device-list">
				<text class="section-title">发现设备 ({{ filteredDevices.length }})</text>
				<view class="device-item" v-for="device in filteredDevices" :key="device.deviceId"
					@click="connectToDevice(device)" :class="{'connecting': connectingDeviceId === device.deviceId}">
					<view class="device-info">
						<text class="device-name">{{ formatDeviceName(device) }}</text>
						<text class="device-id">ID: {{ formatDeviceId(device.deviceId) }}</text>
						<text class="device-mac">MAC: {{ formatMacAddress(device.deviceId) }}</text>
					</view>
					<view class="device-meta">
						<text class="rssi" :class="getRssiClass(device.RSSI)">{{ device.RSSI }} dBm</text>
						<text class="connect-btn">
							{{ connectingDeviceId === device.deviceId ? '配对中...' : '配对' }}
						</text>
					</view>
				</view>
			</view>

			<!-- 实时数据 -->
			<view v-if="connected" class="data-section">
				<text class="section-title">实时重量数据</text>
				<view class="weight-display">
					<text class="weight-value" :class="{'negative': currentWeight.negative}">
						{{ currentWeight.value }}
					</text>
					<text class="weight-unit">{{ currentWeight.unit }}</text>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons">
				<button v-if="!scanning && !connected" class="action-btn primary" @click="startScan">
					<text class="btn-icon">🔍</text>
					<text class="btn-text">扫描 BT04-A 设备</text>
				</button>

				<button v-if="scanning" class="action-btn default" @click="safeStopScan">
					<text class="btn-icon">⏹️</text>
					<text class="btn-text">停止扫描</text>
				</button>

				<button v-if="connected" class="action-btn success" @click="goToHome">
					<text class="btn-icon">🏠</text>
					<text class="btn-text">前往主页</text>
				</button>

				<!-- 断开连接按钮 -->
				<button v-if="connected" class="action-btn warn" @click="manualDisconnect">
					<text class="btn-icon">🔌</text>
					<text class="btn-text">断开连接</text>
				</button>
			</view>

			<!-- 调试信息 -->
			<view class="debug-section">
				<text class="section-title">操作日志</text>
				<view class="debug-content">
					<view class="debug-item" v-for="(log, index) in logs" :key="index">
						<text class="debug-time">{{ log.time }}</text>
						<text class="debug-message">{{ log.message }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import bluetoothService from '@/utils/bluetoothService.js'

	export default {
		data() {
			return {
				// 蓝牙状态
				adapterState: {
					available: false
				},
				// 设备列表
				devices: [],
				// 当前连接状态
				pageConnected: false,
				connecting: false,
				scanning: false,
				// 当前连接/连接中的设备
				connectedDevice: null,
				connectingDeviceId: "",
				// 监听器
				bluetoothListener: null,
				// 日志
				logs: [],
				// 连接超时
				connectTimeout: null,
				// 扫描超时
				scanTimeout: null,

				// 配对设置
				pairingPassword: "1234",
				targetDeviceName: "BT04-A",

				// 重量数据
				currentWeight: {
					value: '0.00',
					negative: false,
					unit: 'kg',
					details: null
				},

				// BLE服务
				serviceId: null,
				characteristicId: null,
				deviceId: null,

				// 设备去重
				duplicateFilter: new Set(),
				// 扫描状态标记
				isDiscoveryStarted: false
			};
		},
		computed: {
			// 同时检查页面状态和服务状态
			connected() {
				return this.pageConnected || bluetoothService.isConnected
			},

			// 过滤设备：信号强度过滤 + 设备名称过滤 + 去重
			filteredDevices() {
				return this.devices.filter(device => {
					// 1. 信号强度过滤
					const goodSignal = device.RSSI > -85;

					// 2. 设备有效性检查（包含名称检查）
					const isValidDevice = this.isValidDevice(device);

					return goodSignal && isValidDevice;
				});
			},

			// 安全的设备名称显示
			connectedDeviceName() {
				if (this.connectedDevice && this.connectedDevice.name) {
					return this.connectedDevice.name;
				}
				if (bluetoothService.connectedDevice) {
					return bluetoothService.formatDeviceName(bluetoothService.connectedDevice);
				}
				return '未知设备';
			}
		},

		onLoad() {
			this.addLog("蓝牙配对页面加载 - 目标设备: " + this.targetDeviceName);

			// 检查服务状态
			this.checkServiceStatus()

			// 监听全局蓝牙数据
			uni.onBLECharacteristicValueChange((res) => {
				this.handleBluetoothData(res)
			})

			this.initBluetooth();

			// 初始化时检查store状态
			this.syncStoreState();
		},

		// 同步store状态
		syncStoreState() {
			const status = this.$store.state.weight.deviceStatus;
			const deviceName = this.$store.state.weight.deviceName;

			// 如果store中已有连接状态，更新页面状态
			if (status === 'connected' || status === 'fully_connected') {
				this.pageConnected = true;
				this.addLog(`从store恢复连接状态: ${status}`);
			}
		},

		onUnload() {
			// 不再清理蓝牙连接，只清理扫描
			this.safeStopScan();
			this.addLog("页面卸载，蓝牙连接保持");
		},

		onShow() {
			// 页面显示时检查服务状态并同步store
			this.checkServiceStatus();
			this.syncStoreState();
		},

		onHide() {
			// 页面隐藏时只停止扫描
			this.safeStopScan();
		},

		methods: {
			// 检查服务状态
			// 检查服务状态 - 增强store同步
			checkServiceStatus() {
				if (bluetoothService.isConnected) {
					this.pageConnected = true
					this.connectedDevice = bluetoothService.connectedDevice
					this.deviceId = bluetoothService.deviceId
					this.serviceId = bluetoothService.serviceId
					this.characteristicId = bluetoothService.characteristicId

					// 确保store状态同步
					this.$store.dispatch('weight/updateStatus', 'connected');
					if (bluetoothService.connectedDevice) {
						const deviceName = bluetoothService.formatDeviceName(bluetoothService.connectedDevice);
						this.$store.commit('weight/SET_DEVICE_NAME', deviceName);
					}

					this.addLog('检测到全局蓝牙连接已建立，已同步到store')
				} else {
					this.pageConnected = false
					// 如果服务未连接，但store显示连接，需要同步
					const storeStatus = this.$store.state.weight.deviceStatus;
					if (storeStatus === 'connected' || storeStatus === 'fully_connected') {
						this.$store.dispatch('weight/updateStatus', 'disconnected');
						this.addLog('检测到store状态不一致，已同步为断开状态');
					}
				}
			},
			// 处理蓝牙数据
			handleBluetoothData(res) {
				try {
					const dataString = bluetoothService.ab2str(res.value)
					this.processWeightData(dataString)

					// 触发全局事件
					uni.$emit('weightDataReceived', dataString)
				} catch (error) {
					this.addLog(`数据处理错误: ${error}`)
				}
			},

			// 手动断开连接
			// 手动断开连接 - 确保store状态同步
			manualDisconnect() {
				// 先更新store状态
				this.$store.dispatch('weight/updateStatus', 'disconnected');
				this.$store.dispatch('weight/updateWeight', ''); // 重置重量数据

				// 调用服务的断开连接方法
				bluetoothService.disconnect()
				this.pageConnected = false
				this.connectedDevice = null
				this.deviceId = null
				this.serviceId = null
				this.characteristicId = null

				this.addLog("手动断开蓝牙连接")
				uni.showToast({
					title: "已断开连接",
					icon: "success"
				})
			},

			// 格式化设备名称
			formatDeviceName(device) {
				if (device.name && device.name.trim() !== '') {
					return device.name;
				} else if (device.localName && device.localName.trim() !== '') {
					return device.localName;
				} else {
					return '';
				}
			},

			// 修改 isValidDevice 方法
			isValidDevice(device) {
				if (!device.deviceId || device.deviceId.length === 0) {
					return false;
				}

				const deviceName = this.formatDeviceName(device);

				// 排除空名称 - 这是关键
				if (!deviceName || deviceName.trim() === '') {
					return false;
				}

				// 排除包含特殊字符的设备
				if (deviceName.includes('') || deviceName.includes('�')) {
					return false;
				}

				// 排除名称过短的设备（通常是无用设备）
				if (deviceName.length < 3) {
					return false;
				}

				return true;
			},

			// 获取信号强度样式
			getRssiClass(rssi) {
				if (rssi > -50) return 'rssi-strong';
				if (rssi > -70) return 'rssi-medium';
				return 'rssi-weak';
			},

			// 添加日志
			addLog(message) {
				const time = new Date().toLocaleTimeString();
				this.logs.unshift({
					time,
					message
				});
				if (this.logs.length > 20) {
					this.logs = this.logs.slice(0, 20);
				}

				console.error('message', message)

			},

			// 格式化设备ID显示
			formatDeviceId(deviceId) {
				return deviceId.length > 12 ? deviceId.substring(0, 8) + '...' : deviceId;
			},

			// 格式化MAC地址显示
			formatMacAddress(deviceId) {
				if (deviceId && deviceId.length >= 12) {
					const mac = deviceId.substring(0, 12).toUpperCase();
					return mac.match(/.{1,2}/g).join(':');
				}
				return deviceId || '未知';
			},

			// 初始化蓝牙
			initBluetooth() {
				this.addLog("初始化蓝牙适配器");

				uni.openBluetoothAdapter({
					success: (res) => {
						this.addLog("✅ 蓝牙适配器初始化成功");
						this.checkBluetoothState();
					},
					fail: (err) => {
						this.addLog(`❌ 蓝牙初始化失败: ${JSON.stringify(err)}`);
						if (err.errCode === 10001) {
							uni.showModal({
								title: "提示",
								content: "蓝牙未开启，请先打开手机蓝牙",
								showCancel: false,
								confirmText: "确定"
							});
						}
					}
				});
			},

			// 清理蓝牙资源 - 修改为只清理扫描
			cleanupBluetooth() {
				this.safeStopScan();
				this.addLog("蓝牙扫描资源已清理");
			},

			// 安全停止扫描（避免重复停止的错误）
			safeStopScan() {
				if (this.scanning && this.isDiscoveryStarted) {
					this.addLog("正在停止扫描设备...");
					this.scanning = false;

					// 清除扫描超时
					if (this.scanTimeout) {
						clearTimeout(this.scanTimeout);
						this.scanTimeout = null;
					}

					uni.stopBluetoothDevicesDiscovery({
						success: () => {
							this.addLog("设备扫描已停止");
							this.isDiscoveryStarted = false;
						},
						fail: (err) => {
							// 忽略停止扫描的错误，可能是已经停止了
							if (err.code !== 10015) {
								this.addLog(`停止扫描失败: ${JSON.stringify(err)}`);
							} else {
								this.addLog("扫描已停止");
								this.isDiscoveryStarted = false;
							}
						}
					});
				} else {
					this.scanning = false;
					this.isDiscoveryStarted = false;
				}
			},

			// 检查蓝牙状态
			checkBluetoothState() {
				uni.getBluetoothAdapterState({
					success: (res) => {
						this.adapterState = res;
						this.addLog(`蓝牙状态: ${res.available ? '已开启' : '未开启'}`);
						this.addLog(`当前扫描状态: ${res.discovering ? '扫描中' : '未扫描'}`);
					},
					fail: (err) => {
						this.addLog(`获取蓝牙状态失败: ${JSON.stringify(err)}`);
					}
				});

				// 监听蓝牙状态变化
				uni.onBluetoothAdapterStateChange((res) => {
					this.adapterState = res;
					this.addLog(
						`蓝牙状态变化: ${res.available ? '已开启' : '未开启'}, 扫描: ${res.discovering ? '进行中' : '已停止'}`
					);
				});
			},

			// 开始扫描设备
			startScan() {
				if (!this.adapterState.available) {
					uni.showToast({
						title: "请先开启蓝牙",
						icon: "none"
					});
					return;
				}

				// 验证配对密码
				if (!this.pairingPassword || this.pairingPassword.trim() === '') {
					uni.showToast({
						title: "请输入配对密码",
						icon: "none"
					});
					return;
				}

				this.addLog(`开始扫描蓝牙设备，目标: ${this.targetDeviceName}，配对密码: ${this.pairingPassword}`);
				this.devices = [];
				this.duplicateFilter.clear();
				this.scanning = true;

				// 先安全停止之前的扫描
				this.safeStopScan();

				// 延迟开始新扫描，确保之前的扫描完全停止
				setTimeout(() => {
					uni.startBluetoothDevicesDiscovery({
						allowDuplicatesKey: false,
						success: (res) => {
							this.addLog("✅ 设备扫描已启动");
							this.isDiscoveryStarted = true;
							this.startDeviceListener();

							// 10秒后自动停止扫描
							this.scanTimeout = setTimeout(() => {
								if (this.scanning) {
									this.addLog("扫描超时，自动停止");
									this.safeStopScan();
									if (this.filteredDevices.length === 0) {
										uni.showToast({
											title: `未找到 ${this.targetDeviceName} 设备`,
											icon: "none"
										});
									}
								}
							}, 10000);
						},
						fail: (err) => {
							this.addLog(`❌ 启动扫描失败: ${JSON.stringify(err)}`);
							this.scanning = false;
							this.isDiscoveryStarted = false;
							uni.showToast({
								title: "扫描失败",
								icon: "none"
							});
						}
					});
				}, 500);
			},

			// 监听设备发现
			startDeviceListener() {
				// 移除之前的监听器
				if (this.bluetoothListener) {
					uni.offBluetoothDeviceFound(this.bluetoothListener);
				}

				this.bluetoothListener = (res) => {
					if (res.devices && res.devices.length > 0) {
						res.devices.forEach(device => {
							// 设备去重
							if (!this.duplicateFilter.has(device.deviceId)) {
								this.duplicateFilter.add(device.deviceId);
								this.devices.push(device);

								const deviceName = this.formatDeviceName(device);
								if (deviceName.includes(this.targetDeviceName)) {
									this.addLog(`✅ 发现目标设备: ${deviceName} (${device.RSSI}dBm)`);
								} else {
									this.addLog(`发现设备: ${deviceName} (${device.RSSI}dBm)`);
								}
							}
						});
					}
				};

				uni.onBluetoothDeviceFound(this.bluetoothListener);
			},

			// 连接设备
			connectToDevice(device) {
				if (this.connecting || this.connected) return;

				// 停止扫描
				this.safeStopScan();

				const deviceName = this.formatDeviceName(device);
				this.addLog(`开始连接设备: ${deviceName}`);
				this.connecting = true;
				this.connectingDeviceId = device.deviceId;

				// 立即更新store状态为连接中
				this.$store.dispatch('weight/updateStatus', 'connecting');

				// 立即设置 connectedDevice，避免后续使用 null
				this.connectedDevice = device;

				// 连接超时设置
				this.connectTimeout = setTimeout(() => {
					if (this.connecting) {
						this.connecting = false;
						this.connectingDeviceId = "";
						this.connectedDevice = null;
						// 更新store状态为超时
						this.$store.dispatch('weight/updateStatus', 'timeout');
						uni.showToast({
							title: "连接超时",
							icon: "none"
						});
						this.addLog("连接超时");
					}
				}, 15000);

				uni.createBLEConnection({
					deviceId: device.deviceId,
					success: () => {
						clearTimeout(this.connectTimeout);
						this.addLog("✅ 设备连接成功，正在发现服务...");
						// 更新store状态为已连接（基础连接）
						this.$store.dispatch('weight/updateStatus', 'connected');
						setTimeout(() => {
							this.discoverServices(device);
						}, 1000);
					},
					fail: (err) => {
						clearTimeout(this.connectTimeout);
						this.connecting = false;
						this.connectingDeviceId = "";
						this.connectedDevice = null;

						// 更新store状态为连接失败
						this.$store.dispatch('weight/updateStatus', 'error');

						this.addLog(`❌ 连接失败: ${JSON.stringify(err)}`);
						uni.showToast({
							title: "连接失败",
							icon: "none"
						});
					}
				});
			},

			// 发现服务
			discoverServices(device) {
				uni.getBLEDeviceServices({
					deviceId: device.deviceId,
					success: (res) => {
						this.addLog(`发现 ${res.services.length} 个服务`);
						// 更新store状态为服务发现中
						this.$store.dispatch('weight/updateStatus', 'discovering_services');

						// 寻找通用串口服务
						const uartService = res.services.find(service =>
							service.uuid.toLowerCase().indexOf('ffe0') > -1 ||
							service.uuid.toLowerCase().indexOf('1101') > -1
						);

						if (uartService) {
							this.serviceId = uartService.uuid;
							this.addLog(`使用串口服务: ${this.serviceId}`);
							this.discoverCharacteristics(device.deviceId, device);
						} else {
							this.addLog("未找到串口服务，尝试使用第一个服务");
							this.serviceId = res.services[0].uuid;
							this.discoverCharacteristics(device.deviceId, device);
						}
					},
					fail: (err) => {
						this.addLog(`服务发现失败: ${JSON.stringify(err)}`);
						// 更新store状态为服务发现失败
						this.$store.dispatch('weight/updateStatus', 'service_discovery_failed');
						this.setupBluetoothConnection(device, false);
					}
				});
			},

			// 发现特征值 - 添加状态更新
			discoverCharacteristics(deviceId, device) {
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: this.serviceId,
					success: (res) => {
						this.addLog(`发现 ${res.characteristics.length} 个特征值`);
						// 更新store状态为特征值发现中
						this.$store.dispatch('weight/updateStatus', 'discovering_characteristics');

						// 寻找可读写的特征值
						const writeChar = res.characteristics.find(char =>
							char.properties.write || char.properties.writeWithoutResponse
						);
						const notifyChar = res.characteristics.find(char =>
							char.properties.notify || char.properties.indicate
						);

						if (notifyChar) {
							this.characteristicId = notifyChar.uuid;
							this.enableNotification(deviceId, device);
						} else if (writeChar) {
							this.characteristicId = writeChar.uuid;
							this.setupBluetoothConnection(device, true);
						} else {
							this.addLog("未找到合适的特征值");
							// 更新store状态为特征值发现失败
							this.$store.dispatch('weight/updateStatus', 'characteristic_discovery_failed');
							this.setupBluetoothConnection(device, false);
						}
					},
					fail: (err) => {
						this.addLog(`特征值发现失败: ${JSON.stringify(err)}`);
						// 更新store状态为特征值发现失败
						this.$store.dispatch('weight/updateStatus', 'characteristic_discovery_failed');
						this.setupBluetoothConnection(device, false);
					}
				});
			},

			// 启用通知
			enableNotification(deviceId, device) {
				// 更新store状态为启用通知中
				this.$store.dispatch('weight/updateStatus', 'enabling_notifications');

				uni.notifyBLECharacteristicValueChange({
					deviceId: deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					state: true,
					success: () => {
						this.addLog("✅ 数据监听已启用");
						// 更新store状态为完全连接
						this.$store.dispatch('weight/updateStatus', 'fully_connected');
						this.setupBluetoothConnection(device, true);
					},
					fail: (err) => {
						this.addLog(`启用通知失败: ${JSON.stringify(err)}`);
						// 更新store状态为通知启用失败
						this.$store.dispatch('weight/updateStatus', 'notification_enable_failed');
						this.setupBluetoothConnection(device, false);
					}
				});
			},

			// 设置蓝牙连接
			setupBluetoothConnection(device, fullSetup = false) {
				// 确保 device 不为 null
				if (!device) {
					this.addLog("❌ 设备信息为空，无法完成连接");
					this.connecting = false;
					this.connectingDeviceId = "";
					// 更新store状态为错误
					this.$store.dispatch('weight/updateStatus', 'error');
					return;
				}

				this.connecting = false;
				this.connectingDeviceId = "";
				this.pageConnected = true;
				this.connectedDevice = device;
				this.deviceId = device.deviceId;

				// 立即更新store连接状态
				this.$store.dispatch('weight/updateStatus', 'connected');

				// 更新设备名称到store
				const deviceName = this.formatDeviceName(device);
				this.$store.commit('weight/SET_DEVICE_NAME', deviceName);

				// 保存到全局服务
				if (fullSetup) {
					bluetoothService.saveConnection(
						device.deviceId,
						this.serviceId,
						this.characteristicId,
						device
					)
				} else {
					// 即使不是完整设置，也要更新store状态
					this.addLog("基础连接建立，更新store状态");
				}

				uni.showToast({
					title: fullSetup ? "配对成功" : "基础连接成功",
					icon: "success"
				});

				this.addLog(`🎉 蓝牙${fullSetup ? '完全' : '基础'}配对完成`);

				// 监听数据接收
				if (fullSetup) {
					this.startDataListener();
				}
			},

			// 开始数据监听
			startDataListener() {
				uni.onBLECharacteristicValueChange((res) => {
					try {
						const value = res.value;
						// 将ArrayBuffer转换为字符串
						const dataString = this.ab2str(value);

						// 本地处理数据
						this.processWeightData(dataString);

						// 同时传递到全局
						const app = getApp();
						if (app && app.handleBluetoothData) {
							app.handleBluetoothData(dataString);
						}
					} catch (error) {
						this.addLog(`数据处理错误: ${error}`);
					}
				});
			},

			// ArrayBuffer转字符串
			ab2str(buffer) {
				const bytes = new Uint8Array(buffer);
				let str = '';
				for (let i = 0; i < bytes.length; i++) {
					str += String.fromCharCode(bytes[i]);
				}
				return str;
			},

			// 字符串转ArrayBuffer
			str2ab(str) {
				const buf = new ArrayBuffer(str.length);
				const bufView = new Uint8Array(buf);
				for (let i = 0; i < str.length; i++) {
					bufView[i] = str.charCodeAt(i);
				}
				return buf;
			},

			// 处理重量数据
			processWeightData(data) {
				this.addLog(`收到数据: ${data}`);

				// 根据不同的数据格式解析重量
				let weightValue = this.parseWeightData(data);
				if (weightValue) {
					this.currentWeight = weightValue;



				}
			},

			// 解析重量数据
			parseWeightData(data) {
				if (!data || typeof data !== 'string') return null;

				// 移除首尾空白字符
				data = data.trim();
				this.$store.dispatch('weight/updateWeight', data);
				// 格式①: +0100.00kg 或 -0100.00kg
				if (data.match(/^[+-]\d+\.\d+kg$/)) {
					const value = data.substring(0, data.length - 2);
					return {
						value: value,
						negative: value.startsWith('-'),
						unit: 'kg'
					};
				}

				// 格式②: 100.00 或 -100.00
				if (data.match(/^-?\d+\.\d+$/)) {
					return {
						value: data,
						negative: data.startsWith('-'),
						unit: 'kg'
					};
				}

				// 格式③: ST,NT,+100.00kg 或 ST,TR,+100.00kg
				if (data.match(/^ST,(NT|TR),[+-]\d+\.\d+kg$/)) {
					const parts = data.split(',');
					const value = parts[2].substring(0, parts[2].length - 2);
					return {
						value: value,
						negative: value.startsWith('-'),
						unit: 'kg',
						details: {
							mode: parts[1] === 'NT' ? '净重' : '毛重'
						}
					};
				}

				// 格式⑤: G.W.: 100.00 kg 等
				if (data.includes('G.W.:') && data.includes('T.W.:') && data.includes('N.W.:')) {
					const lines = data.split('\n');
					const details = {};
					lines.forEach(line => {
						if (line.includes('G.W.:')) details.gross = line.match(/\d+\.\d+/)?.[0];
						if (line.includes('T.W.:')) details.tare = line.match(/\d+\.\d+/)?.[0];
						if (line.includes('N.W.:')) {
							const netMatch = line.match(/-?\d+\.\d+/);
							details.net = netMatch?.[0];
						}
					});

					return {
						value: details.net || '0.00',
						negative: (details.net && details.net.startsWith('-')) || false,
						unit: 'kg',
						details: details
					};
				}

				// 默认尝试提取数字
				const numberMatch = data.match(/-?\d+\.\d+/);
				if (numberMatch) {
					return {
						value: numberMatch[0],
						negative: numberMatch[0].startsWith('-'),
						unit: 'kg'
					};
				}

				return null;
			},

			// 前往主页
			goToHome() {
				this.addLog("前往主页");
				uni.reLaunch({
					url: '/pages/index'
				});
			}
		}
	};
</script>

<style>
	.page {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.container {
		max-width: 750rpx;
		margin: 0 auto;
	}

	/* 状态指示区域 */
	.status-section {
		margin-bottom: 30rpx;
	}

	.status-item {
		display: flex;
		align-items: center;
		padding: 20rpx 24rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		background-color: white;
	}

	.status-item.success {
		border-left: 6rpx solid #4caf50;
	}

	.status-item.warn {
		border-left: 6rpx solid #ff9800;
	}

	.status-item.info {
		border-left: 6rpx solid #2196f3;
	}

	.status-icon {
		font-size: 36rpx;
		margin-right: 16rpx;
	}

	.status-text {
		font-size: 28rpx;
		color: #333;
	}

	/* 配对设置 */
	.pairing-section {
		margin-bottom: 30rpx;
		padding: 24rpx;
		background-color: white;
		border-radius: 12rpx;
	}

	.input-group {
		margin-bottom: 20rpx;
	}

	.input-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 12rpx;
		font-weight: 500;
	}

	.input-field {
		width: 100%;
		padding: 0 20rpx;
		height: 2.5rem;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;
		background-color: #fafafa;
	}

	.input-tips {
		margin-top: 16rpx;
	}

	.tips-text {
		font-size: 24rpx;
		color: #666;
	}

	/* 设备列表 */
	.device-list {
		margin-bottom: 40rpx;
	}

	.section-title {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.device-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		margin-bottom: 16rpx;
		background-color: white;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
		transition: all 0.2s;
		border: 2rpx solid transparent;
	}

	.device-item:active {
		background-color: #f5f5f5;
		transform: scale(0.98);
	}

	.device-item.connecting {
		background-color: #e3f2fd;
		border: 2rpx solid #2196f3;
	}

	.device-info {
		flex: 1;
	}

	.device-name {
		display: block;
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 8rpx;
	}

	.device-id {
		display: block;
		font-size: 24rpx;
		color: #666;
		font-family: monospace;
		margin-bottom: 4rpx;
	}

	.device-mac {
		display: block;
		font-size: 20rpx;
		color: #888;
		font-family: monospace;
	}

	.device-meta {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.rssi {
		font-size: 24rpx;
		margin-bottom: 8rpx;
		font-family: monospace;
	}

	.rssi-strong {
		color: #4caf50;
	}

	.rssi-medium {
		color: #ff9800;
	}

	.rssi-weak {
		color: #f44336;
	}

	.connect-btn {
		font-size: 24rpx;
		color: #007aff;
		font-weight: 500;
	}

	/* 操作按钮 */
	.action-buttons {
		margin-top: 40rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.action-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		border-radius: 12rpx;
		border: none;
		font-size: 32rpx;
		transition: all 0.2s;
	}

	.action-btn.primary {
		background-color: #007aff;
		color: white;
	}

	.action-btn.success {
		background-color: #4caf50;
		color: white;
	}

	.action-btn.default {
		background-color: #f0f0f0;
		color: #333;
	}

	.action-btn.warn {
		background-color: #ff9800;
		color: white;
	}

	.action-btn:active {
		transform: scale(0.98);
	}

	.btn-icon {
		font-size: 36rpx;
		margin-right: 12rpx;
	}

	.btn-text {
		font-size: 28rpx;
	}

	/* 实时数据 */
	.data-section {
		margin-bottom: 30rpx;
		padding: 30rpx;
		background-color: white;
		border-radius: 12rpx;
		text-align: center;
	}

	.weight-display {
		display: flex;
		align-items: baseline;
		justify-content: center;
		margin: 20rpx 0;
	}

	.weight-value {
		font-size: 64rpx;
		font-weight: bold;
		color: #4caf50;
		margin-right: 16rpx;
	}

	.weight-value.negative {
		color: #f44336;
	}

	.weight-unit {
		font-size: 32rpx;
		color: #666;
	}

	/* 调试信息 */
	.debug-section {
		margin-top: 40rpx;
		padding: 20rpx;
		background-color: white;
		border-radius: 12rpx;
	}

	.debug-content {
		max-height: 300rpx;
		overflow-y: auto;
	}

	.debug-item {
		padding: 12rpx 0;
		border-bottom: 1rpx solid #e9ecef;
		display: flex;
		align-items: flex-start;
	}

	.debug-item:last-child {
		border-bottom: none;
	}

	.debug-time {
		font-size: 20rpx;
		color: #666;
		min-width: 120rpx;
		font-family: monospace;
	}

	.debug-message {
		font-size: 24rpx;
		color: #333;
		flex: 1;
		font-family: monospace;
		word-break: break-all;
	}
</style>